<?php
class pUserAction extends pBaseAction{

    public function index(){/*{{{*/
        $conds=array();
        if(array_key_exists('q',$_GET)){
            $key=trim($_GET['q']);
            if($key){
                $conds[]="u.account like '%{$key}%'";
            }
        }
        if(array_key_exists('role',$_GET)){
            $role = intval($_GET['role']);
            if($role > 0){
                $conds[] = "u.role={$role}";
            }
        }
        $condstr='';
        if(count($conds)>0){
            $condstr=' and ('.implode(' or ',$conds).' )';
        }
        $dao=new UserModel();
        $count=$dao->where("account not in ('system')".str_replace('u.','',$condstr))->count();
        if($count>0){
            require LIB_PATH.'Util/PageEx.class.php';
            $p=new PageEx($count,12);
            $dbPrefix=C('db_prefix');
            $this->assign('list',$dao->field('u.*,r.name rolename')
                                        ->where("u.account not in ('system')".$condstr)
                                        ->table($dbPrefix.'user u')
                                        ->join($dbPrefix.'role r on r.id=u.role')
                                        ->limit($p->firstRow.','.$p->listRows)
                                        ->select()
                );
            $this->assign('page',$p->show());
        }
        $this->display();
    }/*}}}*/

    public function add(){/*{{{*/
        $this->assign('roles',$this->getRoleList());
        $this->display();
    }/*}}}*/

    public function save(){/*{{{*/
        $dao = new UserModel();
        $rs = $dao->addUser();
        $this->simpleReturn($dao,$rs,sprintf(L('module_save_user_ok'),$rs['account']));
    }/*}}}*/

    public function edit(){
        $id = $this->getId();
        if($id > 0){
            $dao = new UserModel();
            $rs = $dao->where("id={$id}")->find();
            if(false !== $rs){
                $this->assign('rs',$rs);
                $this->assign('roles',$this->getRoleList());
                $this->display();
            }
        }else{
            $this->fail(L('module_edit_user_fail'),L('module_no_such_user'));
        }
    }

    public function update(){
        $dao = new UserModel();
        $rs = $dao->updateUser();
        $this->simpleReturn($dao,$rs,sprintf(L('module_update_user_ok'),$rs['account']));
    }

    private function getRoleList(){
        $dao = new RoleModel();
        return $dao->where('status=1')->select();
    }

}
